package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    //调用dubbo服务
    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public User findByMobile(String mobile) {
        return userApi.findByMobile(mobile);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 登录校验
     */
    public Map loginVerification(String mobile, String code) {
        //1、获取redis中的验证码
        String redisCode = redisTemplate.opsForValue().get("CODE:" + mobile);
        //2、比较用户输入的验证码和redis验证码是否一致
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //2.1 不一致，抛出异常
            throw new BusinessException(ErrorResult.loginError());
        }
        //2.2 一致，删除redis中的验证码数据
        redisTemplate.delete("CODE:" + mobile);
        //3、根据手机号码查询用户
        User user = userApi.findByMobile(mobile);
        //4 如果用户不存在（新用户），注册用户（保存到用户表）
        Boolean isNew = false;
        String type = "0101"; //登录
        if(user == null) {  //新用户
            isNew = true;
            user = new User();
            user.setPassword("123456");
            user.setMobile(mobile);
            Long userId = userApi.save(user);
            user.setId(userId);
            //将用户信息注册到环信
            huanXinTemplate.createUser("hx"+user.getId(),"123456");
            //更新用户的环信账号和密码
            user.setHxUser("hx"+user.getId());
            user.setHxPassword("123456");
            userApi.update(user);
            type = "0102"; //注册
        }

//        //构造消息
//        Map msg = new HashMap();
//        msg.put("userId",user.getId().toString());
//        msg.put("type",type);
//        String logTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        msg.put("logTime",logTime);
//
//        String message = JSON.toJSONString(msg);
//        //登录成功，发送日志消息
//        rabbitTemplate.convertAndSend("tanhua.log.exchange","log.user",message);//交换机，路由键，消息
        mqMessageService.sendLogMessage(user.getId(), type,"log.user",null);

        //5、生成jwt的token字符串
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(tokenMap);
        //6、构建返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;
    }

    //保存用户资料
    public void saveUserInfo(UserInfo info) {
        // 调用api保存用户信息
        userInfoApi.save(info);
    }

    //设置头像
    public void head(Long id, MultipartFile headPhoto) throws IOException {
        //1、上传到阿里云oss
        String imgUrl = ossTemplate.upload(headPhoto.getInputStream(),
                headPhoto.getOriginalFilename());//文件流，文件名
        //2、判断头像中是否包含人脸
        Boolean detect = aipFaceTemplate.detect(imgUrl);
        if(!detect) {
            //不包含（需要删除阿里云的图片：作业）
            throw new BusinessException(ErrorResult.faceError());
        }
        //3、调用API，更新userinfo
        //MP中，只需要指定id和需要更新的字段对象即可
        UserInfo info = new UserInfo();
        info.setId(id);
        info.setAvatar(imgUrl);
        userInfoApi.update(info);
    }
}
